package com.zhaonongzi.tms.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LBSUtil {

	static Logger logger = Logger.getLogger(LBSUtil.class) ;
    // route matrix API URL
    private static final String ROUTE_URL = "http://api.map.baidu.com/routematrix/v2/driving";	// driving,riding,walking
    private static final String ROUTE_AK = "q3HHzbF8zWH3iTG3VfS6VVbQZUS3PfnW";
    private static final String ROUTE_AK2 = "iu5zSvnNXHS7ofdlTYnPSYWg";
    private static final String OUTPUT_JSON = "json";	// json, xml
    private static final String OUTPUT_XML = "xml";	// json, xml
    private static final String GEOCODER_URL = "http://api.map.baidu.com/geocoder/v2/";
    private static final String GEOCODER_AK = "5M4gZIjzFFKTHy0Z7SzKMRqFV7ltp76P";
    private static final String GEOCODER_AK2 = "wDOFtoPjgmXsOqgFiZRxNQ8cCXXV9aQo";
    
    private static double EARTH_RADIUS = 6378.137;//地球半径


    public static Map getResult(String origin,String destination,String ak,String url,String output) {
        Assert.hasText(origin,"origin:不能为空.");
        Assert.hasText(destination,"destination:不能为空.");
        Assert.hasText(output,"output:不能为空.");
        Assert.hasText(ak,"ak:不能为空.");

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("origins", origin));
        params.add(new BasicNameValuePair("destinations", destination));
        params.add(new BasicNameValuePair("output", output));
        params.add(new BasicNameValuePair("ak", ak));

        String respStr = HttpClientUtil.get(url, params);
        logger.debug("Route Matrix resp : " + respStr);
        Map m = (Map)(JSON.parse(respStr)) ;
        return m ;
    }

    /**
     * 获取两个经纬度的行车距离(米)
     * @param origin 起
     * @param destination 止
     * @return
     */
    public static String getDistance(String origin,String destination) {
        Map r ;
        try {
            r = getResult(origin,destination,ROUTE_AK2,ROUTE_URL,OUTPUT_JSON);
            List<Map> map = JSON.parseArray(r.get("result").toString(), Map.class);
            logger.info("获取距离成功.");
            return JSON.parseObject(map.get(0).get("distance").toString(),Map.class).get("value").toString() ;
        } catch (Exception e) {
            logger.info("获取距离失败", e);
        }

        return null;
    }
    /**
     * 获取两个经纬度的行车距离(米)(批量)
     * @param origins 起
     * @param destinations 止
     * @return
     */
    public static String getDistance(String [] origins,String [] destinations) {
        String origin = StringUtils.join(origins,"|") ;
        String destination = StringUtils.join(destinations,"|") ;
        return getDistance(origin,destination) ;
    }

    /**
     * 从百度获取经纬度
     * @return
     */
    public static Map<String, Object> getGeoPos(String addressTxt) {
        if(StringUtils.isBlank(addressTxt)) return null ;
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("output", OUTPUT_JSON));
        params.add(new BasicNameValuePair("ak", GEOCODER_AK2));
        params.add(new BasicNameValuePair("address", addressTxt));
        try {
            String resp = HttpClientUtil.post(GEOCODER_URL, params);
            JSONObject jsonObj = JSONObject.parseObject(resp);
            jsonObj = jsonObj.getJSONObject("result").getJSONObject("location");
            Map<String, Object> result = new HashMap<>();
            result.put("lat", jsonObj.getString("lat"));
            result.put("lng", jsonObj.getString("lng"));
            logger.info("从LBS成功获取经纬度.[lat:" + jsonObj.getString("lat") + ",lng:" + jsonObj.getString("lng") + "]" );
            return result;
        } catch(Exception e) {
            logger.info("获取经纬度失败", e);
        }
        return null;
    }

    
	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);

		double s = 2 * Math.asin(Math.sqrt(	Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 1000);
		return s;
	}
    
    public static void main(String[] args) {
        //System.out.println(getDistance("40.45,116.34","40.34,116.45"));
//    	System.out.println((getDistance(40.45d,116.34d,40.34d,116.45d)));
//    	System.out.println(getDistance(31.86, 117.27, 30.26, 120.19));
    }
 
}
